package com.dodoke.controller;

import com.dodoke.entity.Role;
import com.dodoke.entity.User;
import com.dodoke.service.RoleService;
import com.dodoke.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @RequestMapping("/list")
    public ModelAndView list(ModelAndView modelAndView){
        // 查询用户列表
        List<User> userList = userService.getAllList();
        modelAndView.addObject("userList",userList);
        // 设置视图
        modelAndView.setViewName("user-list");
        return modelAndView;
    }

    @RequestMapping("/save")
    public String save(User user,Integer[] roleIds){
        // 保存用户
        userService.save(user,roleIds);
        return "redirect:/user/list";
    }

    @RequestMapping("/addIndex")
    public ModelAndView addIndex(ModelAndView modelAndView){
        // 查询出所有的角色
        List<Role> roleList = roleService.getAllList();
        modelAndView.addObject("roleList",roleList);
        // 设置视图
        modelAndView.setViewName("user-add");
        return modelAndView;
    }

    @RequestMapping("/del/{userId}")
    public String delUser(@PathVariable Integer userId){
        userService.delUser(userId);
        return "redirect:/user/list";
    }

    @RequestMapping("/loginUser")
    public String login(String username, String password, HttpSession session){
        System.out.println("执行登录方法...");
        // 根据username和password获取一个user对象
        User user = userService.login(username,password);
        if(user != null){
            session.setAttribute("user",user);
            return "redirect:/index.jsp";
        }
        return "redirect:/login.jsp";
    }
}
